package org.infosec.lc.exercises.castor.dome;

import java.io.IOException;
import java.io.StringReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.infosec.lc.exercises.castor.modle.Person;

/**
	文件名：CastorUDPReceive.java
	作  者：林超
	时  间：2011-7-19下午03:47:30

	功能描述：模拟UDP客户端接收，通过Castor-Unmarshaller将XML转换为Person数据流
	
	pom.xml	:
			
 */
public class CastorUDPReceive implements Runnable{
	private DatagramSocket socket;
	private DatagramPacket packet;
	
	{
		try {
			socket = new DatagramSocket(5000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	private void check(){
		if(socket==null){
			throw new NullPointerException("socket is null");
		}
	}
	
	public static void main(String[] args) {
		Thread t = new Thread(new CastorUDPReceive(),"UDPReceive");
		t.start();
	}

	public void run() {
		try {
			check();
			while(true){
				byte[] buf = new byte[0xff];
				packet = new DatagramPacket(buf,0,0xff);
				socket.receive(packet);
				
				byte[] data = packet.getData();
				System.out.println("Receive data is：" + new String(data,0,packet.getLength(),"UTF-8"));
				
				//注意，new String()时，长度应为packet.getLength();
				StringReader reader = new StringReader(new String(data,0,packet.getLength(),"UTF-8"));
				
				Person person = (Person) Unmarshaller.unmarshal(Person.class, reader);
				
				System.out.println("person name：" + person.getName());
				
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		}
	}
}

